import collections
import json

from django.contrib.auth import authenticate
from django.http import JsonResponse, HttpResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from obs import ObsClient
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication, jwt_decode_handler
from rest_framework.permissions import IsAuthenticated, AllowAny

from ES_utils.es_utils import getClient, return_filter
from project.jwt import *
from rest_framework_jwt.settings import api_settings

from django.contrib.auth.hashers import make_password

# class BookView(ViewSet):
#    authentication_classes = [JSONWebTokenAuthentication,]
#    permission_classes = [IsAuthenticated,]

# @method_decorator(csrf_exempt,name="dispatch")
# class IndexView(View):
# 验证请求头里面的token是否合格，如果合格的话，返回user对象，携带的token不合格的话，则返回错误。
# 注意：如果没有携带token，则该认证不会生效，也不会报错。那么我们在权限组件内做出限制。
#    authentication_classes=[JSONWebTokenAuthentication]
# 检测user对象是否为登录状态，避免了用户没有携带token就访问了此视图且可以访问成功的问题。
#    permission_classes = [IsAuthenticated]
#    def post(self,request,*args,**kwargs):
#        return JsonResponse({'mes':'hello'})
from rest_framework_jwt.serializers import User

from app.models import *


@method_decorator(csrf_exempt, name="dispatch")
class RegisterView(APIView):
    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        # 注册
        email = request.data.get("email")
        password = request.data.get("encrypted_pwd")
        username = request.data.get("username")
        realname = request.data.get("realname")
        code = request.data.get("code")
        nation = ""
        sex = ""
        if request.data.get("country") is not None:
            nation = request.data.get("country")
        if request.data.get("sex") is not None:
            sex = request.data.get("sex")
        if User.objects.filter(email=email).exists():
            return JsonResponse({'errornumber': '-1','msg':'邮箱重复！'})
        if User.objects.filter(username=username).exists():
            return JsonResponse({'errornumber': '-1','msg':'用户名重复！'})
        # 使用django的数据库的filter，按email查找时间最新的一行数据
        emailobj = Email.objects.filter(email=email,type="0").order_by('-time').first()
        if emailobj and str(emailobj.code) == code:
            User.objects.create_user(email=email, username=username, password=password, realname=realname, nation=nation,
                                 sex=sex, admin=0)
            return JsonResponse({'errornumber': '0'})
        else:
            return JsonResponse({'errornumber': '-1','msg':'验证码错误'})

        


@method_decorator(csrf_exempt, name="dispatch")
class RetrievePasswordView(APIView):
    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):

        email = request.data.get("email")
        password = request.data.get("encrypted_pwd")
        code = request.data.get("code")


        if not User.objects.filter(email=email).exists():
            return JsonResponse({'errornumber': '-1','msg':'邮箱未注册！'})

        emailobj = Email.objects.filter(email=email,type="1").order_by('-time').first()
        if emailobj and str(emailobj.code) == code:
            userobj = User.objects.get(email=email)
            userobj.set_password(password)
            userobj.save()
            return JsonResponse({'errornumber': '0'})
        else:
            return JsonResponse({'errornumber': '-1','msg':'验证码错误'})




@method_decorator(csrf_exempt, name="dispatch")
class LoginView(APIView):
    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        email = request.data.get("email")
        username = request.data.get("username")

        password = request.data.get("encrypted_pwd")
        user = None
        if email:
            user = authenticate(username=email, password=password)
        elif username:
            try:
                userobj = User.objects.get(username=username)
            except Exception as e:
                return JsonResponse({'errornumber': "-3", "msg": "用户名不存在"})
            if userobj:
                user = authenticate(username=userobj.email, password=password)
        # 传递用户对象，获取token
        if user is None:
            if not User.objects.filter(email=email).exists():
                return JsonResponse({'errornumber': "-1", "msg": "账号错误"})
            else:
                return JsonResponse({'errornumber': "-2", "msg": "密码错误"})
        else:
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return jwt_response_payload_handler(token, user, request)

@method_decorator(csrf_exempt, name="dispatch")
class GetPersonalInformationView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)
        data = []
        data.append({
            'id':user.id,
            'realname':user.realname,
            'sex':user.sex,
            'email':user.email,
            'sign':user.sign,
            'country':user.nation,
            'username':user.username,
            'isScholar':user.scholar,
            'field':user.field,
            'profile':user.image_url
        })
        return JsonResponse(
            {
            'isSuccess': '0',
            'errormsg':'获取个人信息成功',
            'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class EditPersonalInformationView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        realname = request.data.get("realname")
        sex = request.data.get("sex")
        email = request.data.get("email")
        sign = request.data.get("sign")
        country = request.data.get("country")
        field = request.data.get("field")

        if not realname == "":
            user.realname=realname
        if not sex == "":
            user.sex=sex
        if not email == "":
            user.email = email
        if not sign == "":
            user.sign = sign
        if not country == "":
            user.nation = country
        if not field == "":
            user.field = field
        user.save()
        return JsonResponse(
            {
            'isSuccess': '0',
            'errormsg':'修改个人信息成功',
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class EditPasswordView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        old_password = request.data.get("oldPassword")
        new_password = request.data.get("newPassword")
        if not user.check_password(old_password):
            return JsonResponse(
            {
            'isSuccess': '-1',
            'errormsg':'输入密码错误！',
            }
        )
        else:
            User.objects.filter(id=user_id).update(password=make_password(new_password))
            return JsonResponse(
                {
                    'isSuccess': '0',
                    'errormsg': '修改密码成功！',
                }
            )

@method_decorator(csrf_exempt, name="dispatch")
class GetPaperCollectionView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        data = []
        paper_collections= Collection.objects.filter(uid=user_id)

        for paper_collection in paper_collections:
            if paper_collection.nid == None:
                paper_id = paper_collection.pid
                print(1)
                print(paper_collection.pid)
                # 获取论文信息
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": paper_id
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                data.append({
                    'id':paper_response_json["_source"].get("id"),
                    'name':paper_response_json["_source"].get("title"),
                    'time':paper_collection.time,
                    'abstract':paper_response_json["_source"].get("abstract")
                })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获取论文收藏成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class GetNoteCollectionView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        data = []
        note_collections= Collection.objects.filter(uid=user_id)
        for note_collection in note_collections:
            if note_collection.pid == None:
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": note_collection.nid.pid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                data.append({
                    'id':note_collection.nid.id,
                    'introduction':note_collection.nid.introduction,
                    'time':note_collection.time,
                    'paper_id': paper_response_json["_source"].get("id"),
                    'paper_name': paper_response_json["_source"].get("title")
                })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获取笔记收藏成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class GetNoteView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        data = []
        notes = Note.objects.filter(uid = user_id)

        for note in notes:
            # 获取论文信息
            Json_paperbody = {
                "query": {
                    "match": {
                        "id": note.pid
                    }
                }
            }
            client = getClient()
            paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
            paper_response_json = json.loads(json.dumps(paper_response))
            data.append({
            'id':note.id,
            'introduction':note.introduction,
            'time':note.time,
            'paper_id':paper_response_json["_source"].get("id"),
            'paper_name':paper_response_json["_source"].get("title")
        })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获得笔记成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class GetSetView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获得个人设置成功',
                'isNoteCommentable':user.isNoteCommentable,
                'isNoteVisible':user.isNoteVisible,
                'isLiteratureCommentable':user.isLiteratureCommentable,
                'isCollectionVisible':user.isCollectionVisible,
                'color':user.color,
                'language':user.language
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class EditSetView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        isNoteCommentable = request.data.get("isNoteCommentable")
        isNoteVisible = request.data.get("isNoteVisible")
        isLiteratureCommentable = request.data.get("isLiteratureCommentable")
        isCollectionVisible = request.data.get("isCollectionVisible")
        color = request.data.get("color")
        language = request.data.get("language")

        if not isNoteCommentable == "":
            if isNoteCommentable == "true":
                user.isNoteCommentable = True
            else:
                user.isNoteCommentable = False
        if not isNoteVisible == "":
            if isNoteVisible == "true":
                user.isNoteVisible = True
            else:
                user.isNoteVisible = False
        if not isLiteratureCommentable == "":
            if isLiteratureCommentable == "true":
                user.isLiteratureCommentable = True
            else:
                user.isLiteratureCommentable = False
        if not isCollectionVisible == "":
            if isCollectionVisible == "true":
                user.isCollectionVisible = True
            else:
                user.isCollectionVisible = False
        if not color == "":
            user.color = color
        if not language == "":
            user.language = language
        user.save()

        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '修改个人设置成功',
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class GetPaperCommentView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        data = []
        comment0s = Comment.objects.filter(uid_0 = user_id)
        comment1s = Comment.objects.filter(uid_1 = user_id)
        for comment in comment0s:
            if not comment.pid == None:
                # 获取论文信息
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": comment.pid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                data.append({
                    'id':paper_response_json["_source"].get("id"),
                    'comment_id':comment.id,
                    'name':paper_response_json["_source"].get("title"),
                    'content':comment.content,
                    'time':comment.time
                })
        for comment in comment1s:
            if not comment.pid == None:
                # 获取论文信息
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": comment.pid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                data.append({
                    'id':paper_response_json["_source"].get("id"),
                    'comment_id':comment.id,
                    'name':paper_response_json["_source"].get("title"),
                    'content':comment.content,
                    'time':comment.time
                })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获取论文评论成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class GetNoteCommentView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        data = []
        comment0s = Comment.objects.filter(uid_0 = user_id)
        comment1s = Comment.objects.filter(uid_1 = user_id)
        for comment in comment0s:
            if not comment.nid == None:
                data.append({
                    'id':comment.nid.id,
                    'comment_id':comment.id,
                    'introduction':comment.nid.introduction,
                    'content': comment.content,
                    'time':comment.time
                })
        for comment in comment1s:
            if not comment.nid == None:
                data.append({
                    'id':comment.nid.id,
                    'comment_id':comment.id,
                    'introduction':comment.nid.introduction,
                    'content': comment.content,
                    'time':comment.time
                })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获取笔记评论成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class DelPaperCollectionView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)
        paper_id = request.data.get("paper_id")
        collection = Collection.objects.get(pid=paper_id,uid=user_id)
        collection.delete()
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '删除论文收藏成功',
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class DelNoteCollectionView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)
        note_id = request.data.get("note_id")
        collection = Collection.objects.get(nid=note_id,uid=user_id)
        collection.delete()
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '删除笔记收藏成功',
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class DelNoteView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)
        note_id = request.data.get("note_id")
        note = Note.objects.get(id=note_id)
        note.delete()
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '删除笔记成功',
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class DelCommentView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)
        comment_id = request.data.get("comment_id")
        comment = Comment.objects.get(id = comment_id)
        comment.delete()
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '删除论文评论成功',
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class SearchPaperCollectionView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        search_content = request.data.get("content")
        collections = Collection.objects.filter(uid = user_id)

        data = []
        for collection in collections:
            if not collection.pid == None:
                # 获取论文信息
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": collection.pid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                if search_content in paper_response_json["_source"].get("title"):
                    data.append({
                    'id':paper_response_json["_source"].get("id"),
                    'name':paper_response_json["_source"].get("title"),
                    'abstract':paper_response_json["_source"].get("abstract"),
                    'time':collection.time
                })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '搜索个人论文收藏成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class SearchNoteCollectionView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        search_content = request.data.get("content")
        collections = Collection.objects.filter(uid = user_id)

        data = []
        for collection in collections:
            if not collection.nid == None and search_content in collection.nid.introduction:
                # 获取论文信息
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": collection.nid.pid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                data.append({
                    'id':collection.nid.id,
                    'introduction':collection.nid.introduction,
                    'time':collection.nid.time,
                    'paper_id':paper_response_json["_source"].get("id"),
                    'paper_name': paper_response_json["_source"].get("title")
                })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '搜索个人笔记收藏成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class SearchNoteView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        search_content = request.data.get("content")
        notes = Note.objects.filter(uid = user_id)

        data = []
        for note in notes:
            if search_content in note.introduction:
                # 获取论文信息
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": note.pid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                data.append({
                'id':note.id,
                'introduction':note.introduction,
                'time':note.time,
                'paper_id':paper_response_json["_source"].get("id"),
                'paper_name':paper_response_json["_source"].get("title")
        })

        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '搜索个人笔记成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class SearchPaperCommentView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        search_content = request.data.get("content")
        data = []

        comment0s = Comment.objects.filter(uid_0=user_id)
        comment1s = Comment.objects.filter(uid_1=user_id)

        for comment in comment0s:
            if comment.nid == None and search_content in comment.content:
                # 获取论文信息
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": comment.pid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                data.append({
                    'id':paper_response_json["_source"].get("id"),
                    'name':paper_response_json["_source"].get("title"),
                    'comment_id':comment.id,
                    'content':comment.content,
                    'time':comment.time,
                })
        for comment in comment1s:
            if comment.nid == None and search_content in comment.content:
                # 获取论文信息
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": comment.pid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                data.append({
                    'id':paper_response_json["_source"].get("id"),
                    'name':paper_response_json["_source"].get("title"),
                    'comment_id':comment.id,
                    'content':comment.content,
                    'time':comment.time
                })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '搜索论文评论成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class SearchNoteComment(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)

        search_content = request.data.get("content")
        data = []

        comment0s = Comment.objects.filter(uid_0=user_id)
        comment1s = Comment.objects.filter(uid_1=user_id)

        for comment in comment0s:
            if comment.pid == None and search_content in comment.content:
                data.append({
                    'id':comment.nid.id,
                    'introduction':comment.nid.introduction,
                    'time':comment.nid.time
                })

        for comment in comment1s:
            if comment.pid == None and search_content in comment.content:
                data.append({
                    'id':comment.nid.id,
                    'introduction':comment.nid.introduction,
                    'time':comment.nid.time
                })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '搜索论文评论成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class UploadProfile(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)
        head = request.FILES.get('profile')
        head_name = head.name
        obsClient = ObsClient(
            access_key_id='KCMJB0LFG2AQTSTMEOHM',
            secret_access_key='HJ3dwKTrTV0NmZaR7z6S2FeeI1Y0k6N2Cbdw0Fka',
            server='https://obs.cn-north-4.myhuaweicloud.com/'
        )
        upload_response = obsClient.putObject("obs-0dcd",head_name,head)
        image_url = "https://" + "obs-0dcd" + "." + "obs.cn-north-4.myhuaweicloud.com" + "/" + head_name
        user.image_url = image_url
        user.save()
        obsClient.close()
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '修改头像成功',
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class GetSubscribeView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)
        subscribes = Subscribe.objects.filter(uid_0 = user_id)
        data = []
        for subscribe in subscribes:
            data.append({
                'id':subscribe.uid_1.id,
                'name':subscribe.uid_1.username,
                'subscribe_id':subscribe.id,
                'time':subscribe.time
            })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获取订阅成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class DelSubscribeView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('user_id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)
        subscribe_id = request.data.get('id')
        subscribe = Subscribe.objects.get(id = subscribe_id)
        subscribe.delete()
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '删除订阅成功',
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class SearchSubscribeView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        isToken = request.data.get('isToken')
        id = request.data.get('id')
        if isToken == "1":
            user = User.objects.get(id=user_id)
        else:
            user = User.objects.get(id=id)
        data = []
        content = request.data.get('content')
        subscribes = Subscribe.objects.filter(uid_0=user_id)
        for subscribe in subscribes:
            if content in subscribe.uid_1.username:
                data.append({
                'id':subscribe.uid_1.id,
                'name':subscribe.uid_1.username,
                'subscribe_id':subscribe.id,
                'time': subscribe.time
            })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '搜索订阅成功',
                'data':data,
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class IndexSubscribeNoteView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        followPeople = []
        people = []
        note = []
        subscribes = Subscribe.objects.filter(uid_0=user_id)
        for subscribe in subscribes:
            author = subscribe.uid_1
            notes = Note.objects.filter(uid = author.id)
            for everynote in notes:
                Json_paperbody = {
                    "query": {
                        "match": {
                            "id": everynote.pid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))[0]
                paper_response_json = json.loads(json.dumps(paper_response))
                note.append({
                    'note_id':everynote.id,
                    'paper_id':paper_response_json["_source"].get("id"),
                    'paper_name':paper_response_json["_source"].get("title"),
                    'note_introduction':everynote.introduction,
                    'likes':everynote.like_number,
                    'collections':everynote.collection_number,
                    'remarks':everynote.comment_number
                })
            people.append({
                'userid':author.id,
                'name':author.username,
                'note':note
            })
            followPeople.append(people)
            note = []
            people = []
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '搜索订阅成功',
                'followPeople':followPeople,
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class IndexSubscribePaperView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        data = []
        subscribes = Subscribe.objects.filter(uid_0=user_id)
        for subscribe in subscribes:
            author = subscribe.uid_1
            if not author.aid == "":
                # 获取论文信息
                Json_paperbody = {
                    "query": {
                        "match": {
                            "authors.id": author.aid
                        }
                    }
                }
                client = getClient()
                paper_response = return_filter(client.search(index="paper", body=Json_paperbody))
                paper_response_json = json.loads(json.dumps(paper_response))
                for paper in paper_response_json:
                    author_list = []
                    for every_author in paper["_source"].get("authors"):
                        author_list.append(every_author.get("name"))
                    data.append({
                    'paper_id': paper["_source"].get("id"),
                    'name': paper["_source"].get("title"),
                    'author': author_list,
                    'cite': paper["_source"].get("n_citation"),
                    'origin': paper["_source"].get("venue"),
                    'date': paper["_source"].get("year"),
                    'intro': paper["_source"].get("abstract")
                })
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获取订阅论文成功',
                'data':data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class GetCommentToMeView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        data = []
        if not user.aid == "":
            Json_paperbody = {
            "query": {
                "match": {
                    "authors.id":user.aid
                }
            }
        }
            client = getClient()
            paper_response = return_filter(client.search(index="paper", body=Json_paperbody))
            paper_response_json = json.loads(json.dumps(paper_response))
            for paper in paper_response_json:
                paper_id = paper["_source"].get("id")
                paper_name = paper["_source"].get("title")
                comments = Comment.objects.filter(pid = paper_id)
                for comment in comments:
                    data.append({
                    'paper_id':paper_id,
                    'comment_id':comment.id,
                    'paper_name':paper_name,
                    'content':comment.content,
                    'time':comment.time
                })

        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获取他人给自己的评论成功',
                'data': data
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class JudgeIsMyselfView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = str(token_user['user_id'])
        id = request.data.get("id")

        if user_id == id:
            flag = 1
        else:
            flag = 0
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '判断成功',
                'flag': flag
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class EsToUserView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        es_id = request.data.get("es_id")
        user_id = ""
        if es_id.isdigit():
            user_id = es_id
        elif User.objects.filter(aid = es_id).exists():
            user_id = User.objects.get(aid = es_id).id
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获取成功',
                'id': user_id
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class UserToEsView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [AllowAny]
    def post(self, request):
        user_id = request.data.get("user_id")
        es_id = ""
        if not user_id.isdigit():
            es_id = user_id
        else:
            user = User.objects.get(id = user_id)
            es_id = user.aid
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '获取成功',
                'id': es_id
            }
        )

@method_decorator(csrf_exempt, name="dispatch")
class ClaimAuthorView(APIView):
    def post(self, request):
        #从token中获取用户id
        authorization = request.META.get("HTTP_AUTHORIZATION")
        token = authorization[4:]
        token_user = jwt_decode_handler(token)
        user_id = token_user['user_id']
        user = User.objects.get(id=user_id)
        file = request.FILES.get("file")
        text = request.data.get("text")
        es_id = request.data.get("es_id")
        file_name = file.name
        obsClient = ObsClient(
            access_key_id='KCMJB0LFG2AQTSTMEOHM',
            secret_access_key='HJ3dwKTrTV0NmZaR7z6S2FeeI1Y0k6N2Cbdw0Fka',
            server='https://obs.cn-north-4.myhuaweicloud.com/'
        )
        upload_response = obsClient.putObject("obs-0dcd",file_name,file)
        image_url = "https://" + "obs-0dcd" + "." + "obs.cn-north-4.myhuaweicloud.com" + "/" + file_name
        obsClient.close()
        new_claim = Claim(uid = user_id , aid = es_id,image_url = image_url,text=text)
        new_claim.save()
        return JsonResponse(
            {
                'isSuccess': '0',
                'errormsg': '认领学者成功'
            }
        )